import { Service } from "egg";
import { IndexCondition } from "../common";
import { StandardProps } from "../model/Standard";

export default class StandardService extends Service {
  /**
   * 根据传入名称查询
   */
  public findByName(standard: string) {
    return this.ctx.model.Standard.findOne({ standard });
  }

  /**
   * 查找列表
   * @param {IndexCondition} condition 查询条件
   */
  public async findList(condition: IndexCondition) {
    const { ctx } = this;
    const { select, pageSize, pageIndex, find } = condition;
    const skip = pageIndex && pageSize ? pageIndex * pageSize : 0;
    const res = await ctx.model.Standard.find(find ? find : {})
      .select(select)
      .skip(skip)
      .limit(typeof pageSize === "number" ? pageSize : 10)
      .lean();
    const count = await ctx.model.Standard.find(find ? find : {}).count();
    return {
      count,
      list: res,
      pageSize: pageSize !== undefined ? pageSize : 10,
      pageIndex: pageIndex !== undefined ? pageIndex + 1 : 1,
    };
  }

  /**
   * 添加数据
   * @param data 规格添加
   */
  public async add(data) {
    const { ctx } = this;
    const _data: Partial<StandardProps> = {
      ...data,
    };
    return await ctx.model.Standard.create(_data);
  }
}
